import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRouters: []
}

const mutations = {
  SET_ROUTERS: (state, routes) => {
    state.addRouters = routes
    state.routes = constantRoutes.concat(routes)
  }
}

function getChildren(arr) {
  const children = []
  arr.forEach(ele => {
    const r = {
      path: ele.path,
      name: ele.name,
      resource: ele.resource,
      component: (resolve) => require([`@/views/${ele.resource}`], resolve),
      hidden: ele.hidden,
      meta: { title: ele.title, icon: ele.icon }
    }
    if (ele.children && ele.children.length > 0) {
      r.children = getChildren(ele.children)
    }
    children.push(r)
  })
  return children
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTERS', accessedRoutes)
      resolve(accessedRoutes)
    })
  },
  MenusRoutes({ commit }, data) {
    return new Promise(resolve => {
      const { menus } = data
      const accessedRouters = menus.map(element => {
        const m = {
          path: element.path,
          name: element.name,
          resource: element.resource,
          component: Layout,
          hidden: element.hidden,
          meta: { title: element.title, icon: element.icon }
        }
        if (element.children) {
          const children = getChildren(element.children)
          m.children = children
        }
        return m
      })
      commit('SET_ROUTERS', accessedRouters)
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
